package com.atguigu.gmall.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.oms.entity.OrderItemEntity;
import com.atguigu.gmall.oms.feign.GmallPmsClient;
import com.atguigu.gmall.oms.feign.GmallSmsClient;
import com.atguigu.gmall.oms.feign.GmallUmsClient;
import com.atguigu.gmall.oms.service.OrderItemService;
import com.atguigu.gmall.oms.vo.OrderItemVo;
import com.atguigu.gmall.oms.vo.OrderSubmitVo;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.oms.mapper.OrderMapper;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {
    @Autowired
    GmallPmsClient pmsClient;
    @Autowired
    GmallSmsClient smsClient;
    @Autowired
    GmallUmsClient umsClient;
    @Autowired
    OrderItemService orderItemService;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<OrderEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return new PageResultVo(page);
    }

    /**
     *
     * 保存订单表
     * baseMapper.insert(orderEntity);
     * 保存订单详情表  oms_order_item
     * orderItemService.saveBatch(List<OrderItemEntity> itemEntities);
     *
     * 为什么一个是全部放到一个orderEntity里插入，一个是批量插入List<OrderItemEntity> itemEntities
     * 原因是OrderSubmitVo里送货清单是List<OrderItemVo>items匹配的是订单详情，
     *
     *最好从数据库中查，orderSubmitVo不一定是实时的
     */

    @Override
    @Transactional
    //4.下单
    public OrderEntity saveOrder(OrderSubmitVo orderSubmitVo, Long userId) {
        // 保存订单表
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setUserId(userId);
        ResponseVo<UserEntity> userEntityResponseVo = umsClient.queryUserById(userId);
        UserEntity userEntity = userEntityResponseVo.getData();
        if (userEntity !=null) {
            orderEntity.setUsername(userEntity.getUsername());
        }
        orderEntity.setOrderSn(orderSubmitVo.getOrderToken());
        orderEntity.setCreateTime(new Date());
        orderEntity.setTotalAmount(orderSubmitVo.getTotalPrice());
        orderEntity.setPayAmount(orderSubmitVo.getTotalPrice());
        orderEntity.setIntegration(orderSubmitVo.getBounds()-10);
        orderEntity.setPayType(orderSubmitVo.getPayType());//支付方式【1->支付宝；2->微信；3->银联； 4->货到付款；】
        orderEntity.setSourceType(0);//订单来源[0->PC订单；1->app订单]
        orderEntity.setStatus(0);//订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单】
        orderEntity.setDeliveryCompany(orderSubmitVo.getDeliveryCompany());
        // TODO：根据送货清单中的skuId查询积分优惠，进而求和
        UserAddressEntity address = orderSubmitVo.getAddress();
        if (address!=null) {
            orderEntity.setReceiverAddress(address.getAddress());//详细地址
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());//收货人邮编
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverRegion(address.getRegion());
        }
        orderEntity.setDeleteStatus(0);//删除状态【0->未删除；1->已删除】
        orderEntity.setUseIntegration(orderSubmitVo.getBounds());

        baseMapper.insert(orderEntity);

        // 保存订单详情表  oms_order_item
        //orderSubmitVo和orderItemVo
        List<OrderItemVo> items = orderSubmitVo.getItems();
        if (!CollectionUtils.isEmpty(items)) {
            List<OrderItemEntity> itemEntities = items.stream().map(orderItemVo -> {
                OrderItemEntity itemEntity = new OrderItemEntity();
                itemEntity.setOrderId(orderEntity.getId());
                itemEntity.setOrderSn(orderSubmitVo.getOrderToken());
                // sku相关信息
                ResponseVo<SkuEntity> skuEntityResponseVo = pmsClient.querySkuById(orderItemVo.getSkuId());
                SkuEntity skuEntity = skuEntityResponseVo.getData();
                if (skuEntity != null) {
                    itemEntity.setSkuId(skuEntity.getId());
                    itemEntity.setSkuName(skuEntity.getName());
                    itemEntity.setSkuPic(skuEntity.getDefaultImage());
                    itemEntity.setSkuPrice(skuEntity.getPrice());
                    itemEntity.setSkuQuantity(orderItemVo.getCount().intValue());
                    itemEntity.setCategoryId(skuEntity.getCategoryId());
                    // spu相关信息
                    ResponseVo<SpuEntity> spuEntityResponseVo = pmsClient.querySpuById(skuEntity.getSpuId());
                    SpuEntity spuEntity = spuEntityResponseVo.getData();
                    if (spuEntity != null) {
                        itemEntity.setSpuId(spuEntity.getId());
                        itemEntity.setSpuName(spuEntity.getName());
                    }
                    // spu描述信息
                    ResponseVo<SpuDescEntity> spuDescEntityResponseVo = pmsClient.querySpuDescById(skuEntity.getSpuId());
                    SpuDescEntity spuDescEntity = spuDescEntityResponseVo.getData();
                    if (spuDescEntity != null) {
                        itemEntity.setSpuPic(spuDescEntity.getDecript());
                    }
                    // 品牌信息
                    ResponseVo<BrandEntity> brandEntityResponseVo = pmsClient.queryBrandById(skuEntity.getBrandId());
                    BrandEntity brandEntity = brandEntityResponseVo.getData();
                    if (brandEntity != null) {
                        itemEntity.setSpuBrand(brandEntity.getName());
                    }
                }
                // 查询销售属性
                ResponseVo<List<SkuAttrValueEntity>> responseVo = pmsClient.querySaleAttrValueBySkuId(orderItemVo.getSkuId());
                List<SkuAttrValueEntity> skuAttrValueEntities = responseVo.getData();
                itemEntity.setSkuAttrsVals(JSON.toJSONString(skuAttrValueEntities));

                return itemEntity;
            }).collect(Collectors.toList());
            orderItemService.saveBatch(itemEntities);
        }

        return orderEntity;
    }

}